from flask import Blueprint, request, render_template, redirect, session
from werkzeug.security import generate_password_hash, check_password_hash
from models import *

user = Blueprint("user", __name__)

def checklogin(func):
    def inner(*args,**kwargs):
        if session.get("username"):
            return func(*args,**kwargs)
        else:
            return redirect("/login")
    return inner

@user.route("/reg", methods=["GET", "POST"])
def reg():
    if request.method == "GET":
        return render_template("reg.html")
    else:
        username = request.form.get("username")
        password = request.form.get("password")
        if 6 <= len(username) <= 8 and 8 <= len(password) <= 10:
            users = User(username=username, password=generate_password_hash(password, method="pbkdf2:md5"))
            db.session.add(users)
            db.session.commit()
            return {"msg":"注册成功"}
        else:
            return {"msg":"用户名及密码长度不符"}


@user.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        username = request.form.get("username")
        password = request.form.get("password")
        user = User.query.filter(User.username == username).first()
        ret = check_password_hash(user.password, password)
        if user and check_password_hash(user.password, password):
            session["username"] = username
            return {"msg":"登录成功"}
        else:
            return {"msg":"用户或密码不正确"}


@user.route("/goodslist")
@checklogin
def goodslist():
    goodslist = Goods.query.all()
    return render_template("goodslist.html", goodslist=goodslist)